package com.dexgdx.game.action;

import com.badlogic.gdx.Gdx;
import com.dexgdx.game.actor.AbstractActor;
import com.dexgdx.game.actor.Enemy;
import com.dexgdx.game.manager.ActionManager;
import com.dexgdx.game.structure.Region;

public class MoveAction implements IAction {
	
	private AbstractActor actor;
	
	private boolean isFinished;

	public MoveAction(AbstractActor actor, Region target) {
		super();
		ActionManager.addMovingActorTarget(actor, target);
		this.actor = actor;
	}
	
	public MoveAction(AbstractActor actor, Enemy enemy) {
		super();
		ActionManager.addMovingActorTarget(actor, enemy);
		this.actor = actor;
	}

	@Override
	public void runNextStep() {
		takeNextStep();
	}
	
	@Override
	public boolean isFinished() {
		return isFinished;
	}
	
	private void takeNextStep(){
		Region target = actor.getMovingTarget();
		float deltaX = target.getX() - actor.getX();
		float deltaY = target.getY() - actor.getY();
		double divider = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
		int newX = (int) ((10 * deltaX) / divider);
		int newY = (int) ((10 * deltaY) / divider);
		
		Region nextRegion = new Region();
		nextRegion.setX(actor.getX() + newX);
		nextRegion.setY(actor.getY() + newY);
		nextRegion.setHeight(actor.height);
		nextRegion.setWidth(actor.width);

		if(target.isSolidRegion()){
			if(nextRegion.overlaps(target)){
				isFinished = true;
				ActionManager.removeMovingActorTarget(actor);
			}
			else {
				actor.setFromRegion(nextRegion);
				Gdx.graphics.requestRendering();
			}
		}
		else {
			actor.setFromRegion(nextRegion);
			if(actor.isStepCloseTo(target)){
				actor.setFromRegion(target);
				isFinished = true;
				ActionManager.removeMovingActorTarget(actor);
			}
			Gdx.graphics.requestRendering();
		}
	}
	
}
